package com.ctsi.framework.security.resources.conf;

import com.ctsi.framework.common.exception.CoreErrorConstant;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.framework.security.core.authorize.AuthorizeConfigManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhangjw
 * @Date: 2018/7/25 11:44
 * @Description: 全局配置资源服务器
 */
@Configuration
@EnableResourceServer
@ComponentScan(basePackageClasses = {AuthorizeConfigManager.class})
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(ResourceServerConfiguration.class);

    @Autowired
    private AuthorizeConfigManager authorizeConfigManager;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.formLogin().loginPage("/user/login")
                .successHandler(successHandler())
                .failureHandler(failureHandler());
        http.headers().frameOptions().sameOrigin();
        http
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> {
                    logger.error("Resource Server Author faild,{}", authException);
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"555555555555555555");
                }
                );
        this.authorizeConfigManager.config(http.authorizeRequests());
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationEntryPoint((request, response, authException) -> {
//            Map<String, Object> map = new HashMap<String, Object>();
//            Throwable cause = authException.getCause();
//            if(cause instanceof InvalidTokenException) {
//                map.put("code", RespCode.INVALID_TOKEN);//401
//                map.put("msg", "无效的token");
//            }else{
//                map.put("code", RespCode.UN_LOGIN);//401
//                map.put("msg", "访问此资源需要完全的身份验证");
//            }
//            map.put("data", authException.getMessage());
//            map.put("success", false);
//            map.put("path", request.getServletPath());
//            map.put("timestamp", String.valueOf(new Date().getTime()));
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_OK);
            try {
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(response.getOutputStream(), UnifiedResponse.error(CoreErrorConstant.TOKEN_AUTH_CHECK_ERROR,"请重新登陆!"));
            } catch (Exception e) {
                throw new ServletException();
            }
        });
                //.accessDeniedHandler(new CustomAccessDeniedHandler());
    }

    @Bean
    public AuthenticationSuccessHandler successHandler(){
        return new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                // TODO: 登陆成功以后的逻辑
                System.out.println(authentication.getName()+" 登陆成功!");
            }
        };
    }

    @Bean
    public AuthenticationFailureHandler failureHandler(){
        return new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                // TODO: 登陆失败以后的逻辑
                System.out.println(" 登陆失败!"+exception.getMessage());
            }
        };
    }

}
